﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Collections;
using System.Threading;

namespace ClickrDesktop
{
    public partial class FormPollResults : Form
    {
        #region Variables
        private List<Models.QuestionList> polls = new List<Models.QuestionList>();
        private int current_slide = 0;
        
        private bool isRequestInProcess = false;
        private static FormPollResults inst;
        #endregion

        #region Graph and List
        public static FormPollResults GetForm
        {
            get
            {
                if (inst == null || inst.IsDisposed)
                    inst = new FormPollResults();
                return inst;
            }
        }
        class ListViewItemComparer : IComparer {
            private int col;
            private SortOrder order;
            public ListViewItemComparer() {
                col=0;
                order = SortOrder.Ascending;
            }
            public ListViewItemComparer(int column, SortOrder order) 
            {
                col=column;
                this.order = order;
            }
            public int Compare(object x, object y)
            {
                int returnVal;
                // Determine whether the type being compared is a date type.
                try
                {
                    // Parse the two objects passed as a parameter as a DateTime.
                    System.DateTime firstDate =
                            DateTime.Parse(((ListViewItem)x).SubItems[col].Text);
                    System.DateTime secondDate =
                            DateTime.Parse(((ListViewItem)y).SubItems[col].Text);
                    // Compare the two dates.
                    returnVal = DateTime.Compare(firstDate, secondDate);
                }
                // If neither compared object has a valid date format, compare
                // as a string.
                catch
                {
                    // Compare the two items as a string.
                    returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
                                ((ListViewItem)y).SubItems[col].Text);
                }
                // Determine whether the sort order is descending.
                if (order == SortOrder.Descending)
                    // Invert the value returned by String.Compare.
                    returnVal *= -1;
                return returnVal;
            }
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 1)
            {
                string logToGet = listView1.SelectedItems[0].Text;
                label6.Text = listView1.SelectedItems[0].SubItems[1].Text;
                if (listView1.SelectedItems[0].SubItems[2].Text.Equals(""))
                {
                    label9.Text = "N/A";
                }
                else
                {
                    label9.Text = listView1.SelectedItems[0].SubItems[2].Text;
                }

                label7.Text = listView1.SelectedItems[0].SubItems[3].Text;
                label8.Text = listView1.SelectedItems[0].SubItems[4].Text;
            }
        }
        #endregion

        #region From and Timer Tick
        public FormPollResults()
        {
            InitializeComponent();
            
            this.FormClosing += new FormClosingEventHandler(btn_exit_Click);
            FormClickrDesktop.stopPollResultTimer = false;

            timer.Interval = Convert.ToInt32( System.Configuration.ConfigurationManager.AppSettings["time"].ToString()) * 1000;
            //Thread.Sleep(15000);
            timer.Start();
        }
        private void FormPollResults_Load(object sender, EventArgs e)
        {
            listView1.Columns.Add(new ColumnHeader(""));
            listView1.Columns.Add(new ColumnHeader(""));
            listView1.Columns.Add(new ColumnHeader(""));
            listView1.Columns[0].Text = "";
            listView1.Columns[0].Width = 20;
            listView1.Columns[1].Text = "";
            listView1.Columns[1].Width = 180;
            listView1.Columns[2].Text = "";
            listView1.Columns[2].Width = 30;

            chart1.ChartAreas["ChartArea1"].AxisY.LabelStyle.Format = "{0.} %";
            chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.Enabled = false;
            chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.Enabled = false;
            chart1.Series["Series1"].IsValueShownAsLabel = true;
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (!FormClickrDesktop.stopPollResultTimer && !isRequestInProcess)
            {
                isRequestInProcess = true;
                Managers.LogManager.EnterInLogFile("Updating Poll Result via Timer.");
                Managers.User UserManager = new Managers.User();
                String json = UserManager.pull_polls(FormClickrDesktop.user);
                if (!json.Equals(""))
                {
                    json = "{\"child\":" + json + "}";
                    XmlDocument xDoc = Helpers.XML_Json_Parser.Json_To_XML_Conversion(json);
                    DisplayGrid(xDoc, 1);
                }
                isRequestInProcess = false;
            }
        }
        #endregion

        #region Screen Formulation and Screen Events
        private void btn_left_arrow_Click(object sender, EventArgs e)
        {
            current_slide = (current_slide - 1) % polls.Count;
            if (current_slide < 0) current_slide = current_slide + polls.Count;
            FormulateCurrentGrid(polls[current_slide]);
        }
        private void btn_right_arrow_Click(object sender, EventArgs e)
        {
            current_slide = (current_slide + 1) % polls.Count;
            FormulateCurrentGrid(polls[current_slide]);
        }

        private void FormulateCurrentGrid(Models.QuestionList questionList)
        {
            //listView1.Clear();

            grid_question.Rows[0].Cells["Q"].Value = "Q";
            grid_question.Rows[0].Cells["question"].Value = questionList.question;
            grid_question.Height = grid_question.Rows[0].GetPreferredHeight(0, DataGridViewAutoSizeRowMode.AllCells, true) + 5;

            label_description.Text = questionList.description;

            grid_options.Location = new Point(grid_options.Location.X, grid_question.Location.Y + grid_question.Height);
            grid_options.Rows.Clear();

            int height = 10;
            for (int i = 0; i < questionList.options.Count; i++)
            {
                int index = grid_options.Rows.Add();
                if (questionList.correctvalu == i + 1)
                {
                    grid_options.Rows[index].Cells["color"].Style.BackColor = Color.Green;
                }
                else
                {
                    grid_options.Rows[index].Cells["color"].Style.BackColor = Color.Red;
                }

                grid_options.Rows[index].Cells["index"].Value = ((i + 1) % 10).ToString() + ((char)(i + 65)).ToString();
                grid_options.Rows[index].Cells["options"].Value = questionList.options[i];

                height += grid_options.Rows[i].GetPreferredHeight(i, DataGridViewAutoSizeRowMode.AllCells, true);
            }
            grid_options.AllowUserToAddRows = false;
            grid_options.Height = height;
            listView1.Items.Clear();
            listView1.View = View.Details;
            ImageList Imagelist = new ImageList();
            Imagelist.Images.Add(Image.FromFile(Application.StartupPath + @"\Images\ViewResults\clickr_c.png"));
            Imagelist.Images.Add(Image.FromFile(Application.StartupPath + @"\Images\ViewResults\clickr_t.png"));
            listView1.SmallImageList = Imagelist;
            ListViewItem[] lvi = new ListViewItem[questionList.responce.Count];
            for (int i = 0; i < questionList.responce.Count; i++)
            {
                if (questionList.responce[i].device.Equals("TRUE"))
                {
                    lvi[i] = new ListViewItem("", 1);
                }
                else
                {
                    lvi[i] = new ListViewItem("", 0);
                }
                //int result;
                //if (int.TryParse(questionList.responce[i].fname, out result))
                //{
                // Debug.WriteLine("Valid integer: " + result);
                //  lvi[i].SubItems.Add(result);
                //}
                //else
                //{
                lvi[i].SubItems.Add(questionList.responce[i].fname);
                // Debug.WriteLine("Not a valid integer");
                //}

                lvi[i].SubItems.Add(questionList.responce[i].ans);
                lvi[i].SubItems.Add(questionList.responce[i].username);
                lvi[i].SubItems.Add(questionList.responce[i].time.ToString());
                lvi[i].SubItems.Add(questionList.responce[i].device);
            }
            listView1.Items.AddRange(lvi);
            chart1.Series["Series1"].Points.Clear();
            if (questionList.responce.Count != 0)
            {
                for (int i = 0; i < questionList.options.Count; i++)
                {
                    chart1.Series["Series1"].Points.AddXY(i + 0.5, Convert.ToInt32(Convert.ToDouble(questionList.graph[i + 1 + ""]) / questionList.responce.Count * 100));
                    chart1.Series["Series1"].Points[i].AxisLabel = ((i + 1) % 10).ToString() + ((char)(i + 65)).ToString();
                    chart1.Series["Series1"].Points[i].Color = Color.FromArgb(0, 50 * (i + 2) % 255, 0);
                }
            }

        }
        public void DisplayGrid(XmlDocument xDoc, int decesion)
        {
            // Get each node and parse out each question in polls
            //XmlNodeList nodes = xDoc.SelectNodes("/parent/child");
            XmlNodeList nodes = xDoc.SelectNodes("/parent/child");
            foreach (XmlNode node in nodes)
            {
                try
                {

                    String description = node.SelectSingleNode("properties/description/text()").Value;
                    XmlNodeList questions = node.SelectNodes("questions/multichoice");
                    foreach (XmlNode question in questions)
                    {
                        Models.QuestionList questionList = new Models.QuestionList();
                        questionList.description = description;
                        questionList.correctvalu = Convert.ToInt32(question.SelectSingleNode("correctvalue/text()").Value);
                        XmlNodeList responc = question.SelectNodes("responses/response");
                        XmlNodeList options = question.SelectNodes("answers");
                        foreach (XmlNode option in options)
                        {
                            questionList.options.Add(option.SelectSingleNode("answertext/text()").Value);
                        }
                        for (int i = 0; i < options.Count; i++)
                        {
                            questionList.graph[i + 1 + ""] = "0";
                        }
                        questionList.question = question.SelectSingleNode("questiontext/text()").Value;
                        foreach (XmlNode res in responc)
                        {
                            questionList.graph[res.SelectSingleNode("responsestring/text()").Value] = Convert.ToInt32(questionList.graph[res.SelectSingleNode("responsestring/text()").Value]) + 1 + "";

                        }
                        foreach (XmlNode res in responc)
                        {
                            Models.Responce device = new Models.Responce();
                            device.ans = ((Convert.ToInt32(res.SelectSingleNode("responsestring/text()").Value)) % 10).ToString() + ((char)(Convert.ToInt32(res.SelectSingleNode("responsestring/text()").Value) + 64)).ToString();
                            device.fname = res.SelectSingleNode("deviceid/text()").Value;
                            //device.lname = res.SelectSingleNode("deviceid/text()").Value;
                            device.username = res.SelectSingleNode("email/text()").Value;
                            device.device = res.SelectSingleNode("isTurningPointUser/text()").Value;
                            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                            device.time = epoch.AddSeconds(Convert.ToInt64(res.SelectSingleNode("addedtime/text()").Value));
                            questionList.responce.Add(device);
                            //device.time
                        }
                        polls.Add(questionList);
                    }

                }
                catch (Exception ex) { }
            }
            if (decesion == 0)
            {
                FormulateCurrentGrid(polls[current_slide]);
            }
            else
            {
                try
                {
                    base.Invoke(new MethodInvoker(delegate
                    { FormulateCurrentGrid(polls[current_slide]); }));
                }
                catch { }
            }
        }
        #endregion

        #region Button Events
        private void btn_exit_Click(object sender, EventArgs e)
        {
            this.Dispose();
            FormClickrDesktop.stopPollResultTimer = true;
            grid_options.Dispose();
            grid_question.Dispose();
            this.Close();
        }
        private void label2_Click(object sender, EventArgs e)
        {
            tablessControl1.SelectedIndex = 1;
            BringFront(label2);
        }
        private void label3_Click(object sender, EventArgs e)
        {
            tablessControl1.SelectedIndex = 0;
            BringFront(label3);
        }
        private void BringFront(Label label)
        {
            label2.SendToBack();
            label3.SendToBack();
            label.BringToFront();
        }
        #endregion

        #region RadioButtons
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            this.listView1.ListViewItemSorter = new ListViewItemComparer(2, SortOrder.Ascending);
            // Call the sort method to manually sort.
            listView1.Sort();
        }
        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            this.listView1.ListViewItemSorter = new ListViewItemComparer(5, SortOrder.Ascending);
            // Call the sort method to manually sort.
            listView1.Sort();
        }
        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            this.listView1.ListViewItemSorter = new ListViewItemComparer(1, SortOrder.Ascending);
            // Call the sort method to manually sort.
            listView1.Sort();
        }
        private void radioButton4_CheckedChanged(object sender, EventArgs e)
        {
            this.listView1.ListViewItemSorter = new ListViewItemComparer(4, SortOrder.Ascending);
            // Call the sort method to manually sort.
            listView1.Sort();
        }
        #endregion
    }
}
